<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Keu_pemb_pendaftaran_anggota extends MY_Controller {
	
	var $arr_allowed_upload	= array('xls','xlsx');
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('keu_pemb_pendaftaran_anggota_model', 'TabunganAnggota');
		$this->load->model('combo_model', 'Combo');
		$this->load->model('keu_store_procedure_model', 'SP');
		$this->load->model('keu_coa_model', 'Coa');
		$this->secure_session();
	}
	
	function index(){
		$data['title'] = "Pembayaran Pendaftaran Anggota";
		$data['data'] = null;
		$data['data']['date_from'] = date('01/m/Y');
		$data['data']['date_to'] = date('t/m/Y');
		
		viewByTemplate('keu_pemb_pendaftaran_anggota/index', $data, 'grid');
	}
	
	function getdata()
	{
		$this->secure_session();
		echo $this->TabunganAnggota->GetJSON();
	}
	
		
	
	function edit()
	{
		$data['title'] = "Pembayaran Pendaftaran Anggota";
		$data['data'] = $this->TabunganAnggota->GetSingleView(get('id_anggota'), get('no_urut'));
				
		$data['office_data']		= json_encode($this->Combo->SWOffice());
		$data['valuta_data']		= json_encode($this->Combo->SWValuta());
		$data['cost_center_data']	= json_encode($this->Combo->SWCostCenter());
		
		
		
		$data['mode'] = "edit";
		viewByTemplate('keu_pemb_pendaftaran_anggota/form', $data, 'form');
	}

	
	function GetKurs(){
		$arrkurs = $this->TabunganAnggota->GetKurs(post('kd_valuta'), date_format3(post('tgl_pembayaran_pinjaman'), 'YYYY-MM-DD'));
		echo $arrkurs['harga_rata'];
	}
	
	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty = $this->MessageTemplate("ER001");
		$tpl_duplicate = $this->MessageTemplate("ER002");

		
		// Validation
		if (post("kd_kantor") == '') {
			$error->Add("kd_kantor", "Kantor", $tpl_empty);
		}
		
		if (post("tgl_transaksi") == '') {
			$error->Add("tgl_transaksi", "Tanggal Transfer", $tpl_empty);
		}
		
		if (post("kd_valuta") == '') {
			$error->Add("kd_valuta", "Mata Uang", $tpl_empty);
		}
		
		if (toNumber(post("jml_dana")) == '0') {
			$error->Add("jml_dana", "Jumlah Dana", $tpl_empty);
		}
		
		if (post("keterangan") == '') {
			$error->Add("keterangan", "Keterangan", $tpl_empty);
		}
		
		return $error;
	}
	
	function dtl_account_data()
	{
		echo $this->TabunganAnggotaDetail->GetJSON();
	}
	
	function ajax_post()
	{
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";

		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data
				$data	= post_by_key(array('kd_kantor', 'tgl_transaksi',  'keterangan',  'kurs', 'kd_valuta', 'jml_dana'));
				
				
				$data['kurs']			= toNumber($data['kurs']);
				$data['jml_dana']		= toNumber($data['jml_dana']);
				
				
				
				$suffix 	= "/KB/".date_format3(post('tgl_transaksi'), 'MM').'/'.date_format3(post('tgl_transaksi'), 'YYYY');
				$id_dok		= $this->get_data("SELECT (NVL((SELECT MAX(SUBSTR(ID_DOK,0,LENGTH(ID_DOK)-LENGTH('".$suffix."'))) FROM KEU_TRANS_KAS_BANK WHERE SUBSTR(ID_DOK,-1*LENGTH('".$suffix."'),LENGTH('".$suffix."')) = '".$suffix."'),0)+1) CODE FROM DUAL");
				$id_dok		= str_pad($id_dok, 2, '0', STR_PAD_LEFT).$suffix;
				
				$data['id_dok']					= $id_dok;
				$data['id_reff']				= post('id_pinjaman');
				$data['status_transaksi']		= 'Y';
				$data['tgl_transaksi']			= date_format3(post('tgl_transaksi'), 'YYYY-MM-DD');
				$data['keterangan']				.= ' (Simpanan Periode '.post('bulan_tagihan').')';
				$data['create_date']			= NOW;
				$data['create_user']			= USERID;

				$this->TabunganAnggota->Add($data);
				
				
				$this->SP->SP_GL_SIMPANAN_ANGGOTA($id_dok,post('id_anggota'),post('no_urut'));

				$ls_response = "Data Tersimpan";
				
				
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$id_dok	= get('id_dok');
		
		if ($id_dok != "")
		{
			// Delete Single
			$ls_result = $this->TabunganAnggota->DeleteSingle($id_dok);

		}
		else
		{
			
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				$ls_result .= $this->TabunganAnggota->DeleteSingle($row['id_dok']);
			}
		}
		
		echo $ls_result;
	}
	
	function form_import(){
		$data['title'] = "Import Data";
		
		$this->load->view('keu_pemb_pendaftaran_anggota/form_import', $data);
		
	}
	
	function process_upload_file(){
		$is_error		= 0;
		$arr_allowed	= array('xls');
		$config['upload_path']		= APPPATH . '/file/upload/';
		$config['allowed_types']	= $arr_allowed;
		$this->load->library('upload', $config);
		
		$error = new ErrorList();
		
		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");
		$tpl_typefile	= $this->MessageTemplate("ER011");
		$tpl_filesize	= $this->MessageTemplate("ER013");
		$tpl_upload_success = $this->MessageTemplate("CS004");
		
		// Get Server Maximum Upload File Size 
		// (publisher : http://www.kavoir.com/2010/02/php-get-the-file-uploading-limit-max-file-size-allowed-to-upload.html)
		$max_upload		= (int)(@ini_get('upload_max_filesize'));
		$max_post		= (int)(@ini_get('post_max_size'));
		$memory_limit	= (int)(@ini_get('memory_limit'));
		$max_upload_mb	= @min($max_upload, $max_post, $memory_limit);
		$content_length	= (array_key_exists('CONTENT_LENGTH',$_SERVER) ? $_SERVER['CONTENT_LENGTH'] : 0);
		
		// Validation
		$has_file	= false; $arr_uploaded	= array();
		if($content_length/1048576 > $max_upload_mb){
			$ls_response	= $tpl_filesize['message_id'];
			$ls_response	= str_replace('{0}', stringFileSize($content_length), $ls_response);
			$ls_response	= str_replace('{1}', $max_upload_mb.'MB', $ls_response);
			
			$is_error = 1;
		}else{
			$filename	= $_FILES['my_file']['name'];
			$ext		= strtolower(end(explode('.', $filename)));
			
			if(trim($filename) != ''){
				$new_filename	= md5(USERID);
				
				@unlink($config['upload_path'].$new_filename.'.'.$ext);
				
				if(!in_array($ext, $arr_allowed)){
					$ls_response	= $tpl_typefile['message_id'];
					$ls_response	= str_replace('{0}', '["'.$ext.'"]', $ls_response);
					$ls_response	= str_replace('{1}', json_encode($arr_allowed), $ls_response);
					
					$is_error = 1;
				}else if ( !$this->upload->do_upload('my_file'.$i, $new_filename) )
				{
					$ls_response = $this->upload->display_errors('', '');
					
					if(trim($ls_response) == ''){ $is_error = 1; }
				}
			}else{
				$ls_response	= $tpl_empty['message_id'];
				$ls_response	= str_replace('{0}', 'File', $ls_response);

				$is_error = 1;
			}
		}
		
		if($is_error == 1){
			echo '<script type="text/javascript">parent.setLoading(false); parent.$.messager.alert("Error","'.addslashes($ls_response).'","error");</script>';
		}else{
			echo '<script type="text/javascript">parent.f_import_file_to_db("'.$new_filename.'.'.$ext.'");</script>';
		}
	}
	
	function import_file_to_db(){
		$filename 		= post('filename');
		$path 			= APPPATH . '/file/upload/' . $filename;
		
		@set_time_limit(0);				// ignore php timeout
		//@ignore_user_abort(true);		// keep on going even if user pulls the plug*
		
		$this->load->helper('excel_reader');
		error_reporting(E_ALL ^ E_NOTICE);
		$data = new Spreadsheet_Excel_Reader($path);
		$sheet = 0;
		
		$arr_fieldname	= array('FIELD1', 'FIELD2', 'FIELD3', 'FIELD4', 'FIELD5');
		$num_rows	= $data->rowcount($sheet);
		
		$count_success	= 0;
		$count_error	= 0;
		$error_logfile	= APPPATH . '/file/cache/' . _SESSID .'.error_log.txt';
		@unlink($error_logfile);
		
		// Delete Temporary Data
		$this->db->delete('KEU_IMPORT_TAGIHAN', array('SESSID' => _SESSID));
		
		for($i = 2, $max_i = $num_rows; $i<=$max_i; $i++){
			$row = array();
			$row['rows']	= $i;
			for($col=1;$col<=$data->colcount($sheet);$col++) {
				$val		= trim($data->val($i,$col,$sheet));
				$key		= "FIELD".$col;
				
				$row[$key]	= $val;
				
				if(is_date($val)) 
					$row[$key]	= date_format3($val,'YYYY-MM-DD');
				else
					$row[$key]	= $rows = str_replace("'", "", $val);
				
			}
			
			// -- >> Process
			if(count(array_keys($row))>=count($arr_fieldname)){
				$lb_valid = true;
				$ls_error = '';
				
				
				
				if($lb_valid){
					unset($row['rows']);
					$row['SESSID']		= _SESSID;
					$row['INDEX_NO']	= $i-1;
					$row['CREATE_DATE']	= NOW;
					$row['CREATE_ID']	= USERID;
					
					// Insert Temporary Data
					$this->db->insert('KEU_IMPORT_TAGIHAN', $row);
					$count_success++;
				}else{
					$ls_error = 'Line '.str_pad($i, 5, '0', STR_PAD_LEFT).' >> '.$ls_error;
					$count_error++;
					
					write_file($error_logfile, $ls_error."\n", 'a+');
				}
			}
			
		}
		
		$ls_response = "Import Process ".$num_rows." row(s) data Finished<br />- ".$count_success." success<br />- ".$count_error." failed  (".($count_error==0?'':"<a href=\"#\" onclick=\"document.getElementById('if_download').src=gs_path+'/app/download/?file=".end(explode('/',$error_logfile))."&filename=errorlog.txt';\">download log</a>)");
		echo 'setLoading(false); grid_import_reload(); $.messager.alert("Notification","'.addslashes($ls_response).'","ok");';
		
		if($count_success > 0){
			echo "$('#label_file_import, #my_file, #btn_upload').hide(); $('#btn_import, #btn_new_import').fadeIn();";
		}else{
			echo "f_new_import();";
		}
	}
	
	function import_transfer(){
		// ------------------------------
		// Process your data here
		// ------------------------------
		try {
			$this->db->query("BEGIN SP_GL_PROSES_UPLOAD_SIMPANAN('"._SESSID."','".USERID."'); END;");
		} catch(Exception $e) {
			return $e->getMessage();
		}
		
		// Delete Temporary Data
		//$this->db->delete('SAMPLE_IMPORT', array('SESSID' => _SESSID));
		
		echo 'setLoading(false); grid_import_reload(); grid_reload(); /*f_new_import();*/ $.messager.alert("Success","Proses import selesai","ok"); ';
	}
	
	function getimportdata()
	{
		// Ajax Response For Datagrid
		echo $this->TabunganAnggota->GetImportJSON();
	}
}
?>